//
// Created by xueke on 2021/11/8.
//

#include "myWidget.h"

#include <QGridLayout>

#include <QStyle>
#include <QAction>
#include <QApplication>
#include <QUrl>
#include <QMessageBox>
#include <QProcess>
#include <QDebug>
void downloadWork::Download(const QString &url) {
	qDebug()<<"Hello Download";
  int rv;
  aria2::libraryInit();
  aria2::SessionConfig config;
  config.downloadEventCallback = downloadEventCallback;
  aria2::KeyVals options;
  options.push_back(std::pair<std::string, std::string>("check-certificate", "false"));
  session = aria2::sessionNew(options, config);
  aria2::addUri(session,
				nullptr,
				std::vector<std::string>{url.toStdString()},
				aria2::KeyVals());

  auto start=std::chrono::steady_clock::now();
  for (;;) {
	rv = aria2::run(session, aria2::RUN_ONCE);
	if (rv != 1) {
	  break;
	}
	auto now=std::chrono::steady_clock::now();
	auto count=std::chrono::duration_cast<std::chrono::milliseconds>(now-start).count();
	if(count>=1000){
	  start=now;

//	  aria2::GlobalStat gstat=aria2::getGlobalStat(session);
	  aria2::A2Gid gids = aria2::getActiveDownload(session)[0];
	  aria2::DownloadHandle *dh=aria2::getDownloadHandle(session,gids);
	  if(dh){
//		qDebug()<<dh->getCompletedLength();
		emit resultReady({dh->getCompletedLength(),dh->getTotalLength()});
		aria2::deleteDownloadHandle(dh);
	  }

	}
  }
  rv = aria2::sessionFinal(session);
  aria2::libraryDeinit();
}
void downloadWork::shutdown() {

  aria2::shutdown(session);
  aria2::libraryDeinit();

}
 int downloadWork::downloadEventCallback(aria2::Session* session, aria2::DownloadEvent event,
						  aria2::A2Gid gid, void* userData) {
  switch (event) {
	case aria2::EVENT_ON_DOWNLOAD_COMPLETE: qDebug() << "COMPLETE";
	  break;
	case aria2::EVENT_ON_DOWNLOAD_ERROR: qDebug() << "ERROR";
	  break;
	default: return 0;
  }
   return 0;
}
myWidget::myWidget() {
  qRegisterMetaType<std::vector<int64_t>>("std::vector<int64_t>");
  initFace();
  auto *work = new downloadWork;
  work->moveToThread(&workerThread);


  connect(startButton, &QPushButton::clicked, this, &myWidget::startCheck);
  connect(this, &myWidget::goDownload, work, &downloadWork::Download);
  connect(this,&myWidget::shutdownSession,work,&downloadWork::shutdown);
  connect(work,&downloadWork::resultReady,this,&myWidget::updateProgress);
  connect(cancelButton, &QPushButton::clicked, this, &myWidget::cancelDownload);

  workerThread.start();
}

void myWidget::initFace() {
  resize(500, 200);
  lineLink = new QLineEdit("https://download.cnki.net/CAJViewer%207.3.141.self.exe");
  lineLink->setClearButtonEnabled(true);
  progressBar = new QProgressBar();
  startButton =
	  new QPushButton(QApplication::style()->standardIcon(QStyle::SP_MediaPlay), "开始");
  cancelButton=new QPushButton(QApplication::style()->standardIcon(QStyle::SP_MediaStop),"终止");
  auto layout = new QGridLayout;
  layout->addWidget(new QLabel("下载链接"), 0, 0, 1, 1);
  layout->addWidget(lineLink, 0, 1, 1, 3);
  layout->addWidget(new QLabel("下载进度"), 1, 0, 1, 1);
  layout->addWidget(progressBar, 1, 1, 1, 3);
  layout->addWidget(startButton, 2, 1, 1, 1);
  layout->addWidget(cancelButton, 2, 3, 1, 1);

  setLayout(layout);
}
bool myWidget::cancelDownload() {
  return false;
}
void myWidget::startCheck() {
  QString url = lineLink->text().trimmed();
  if (url.isEmpty())
	return;
  const QUrl newUrl = QUrl::fromUserInput(url);
  if (!newUrl.isValid()) {
	QMessageBox::information(this, tr("Error"),
							 tr("Invalid URL: %1: %2").arg(url, newUrl.errorString()));
	return;
  }
  goDownload(url);
}
myWidget::~myWidget() {

}
void myWidget::updateProgress(const std::vector<int64_t> &downloadLength) {
progressBar->setMaximum(int(downloadLength.at(1)));
progressBar->setValue(int(downloadLength.at(0)));

qDebug()<<progressBar->value();
}
void myWidget::closeEvent(QCloseEvent *event) {
  event->accept();
  shutdownSession();
  workerThread.quit();
  workerThread.wait();
}

